import { TUserMsgType } from '@/datatypes/TUserMsg/data';
import { handleAdd, handleRemove, handleRemoveList, handleUpdate, page } from '@/services';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';

import { Button, Drawer } from 'antd';
import React, { useRef, useState } from 'react';
import UpdateForm from "@/pages/TUserMsg/components/UpdateForm";
import { TUserMsgUrl } from '@/Urls';

const TableList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TUserMsgType>();
  const [selectedRowsState, setSelectedRows] = useState<TUserMsgType[]>([]);

  const columns: ProColumns<TUserMsgType>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
   {
       title: '用户Id',
       dataIndex: 'userId',
   },
   {
       title: '状态(0: 未读	  1:已读)',
       dataIndex: 'status',
   },
   {
       title: '消息类型(0: 默认系统，扩展字段 )',
       dataIndex: 'msgType',
   },
   {
       title: '消息内容',
       dataIndex: 'content',
   },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
            setShowDetail(false);
          }}
        >
          更新
        </a>,
        <a
          key="remove"
          onClick={async () => {
            await handleRemove(TUserMsgUrl, record.id);
            if (actionRef.current) {
              await actionRef.current.reload();
            }
            setShowDetail(false);
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<TUserMsgType, API.PageParams>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params) => page(TUserMsgUrl, params)}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemoveList(TUserMsgUrl, selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title="新建"
        width="400px"
        open={createModalVisible}
        onOpenChange={handleModalVisible}
        onFinish={async (value: any) => {
          const success = await handleAdd(TUserMsgUrl, value as TUserMsgType);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
               await actionRef.current.reload();
            }
          }
        }}
      >
      <ProFormText
          rules={[
          {
          required: true,
          message: '用户Id为必填项',
          },
          ]}
          width="md"
          name="userId"
          label={'用户Id'}
          placeholder={'请输入用户Id'}
      />
      <ProFormText
          rules={[
          {
          required: true,
          message: '状态(0: 未读	  1:已读)为必填项',
          },
          ]}
          width="md"
          name="status"
          label={'状态(0: 未读	  1:已读)'}
          placeholder={'请输入状态(0: 未读	  1:已读)'}
      />
      <ProFormText
          rules={[
          {
          required: true,
          message: '消息类型(0: 默认系统，扩展字段 )为必填项',
          },
          ]}
          width="md"
          name="msgType"
          label={'消息类型(0: 默认系统，扩展字段 )'}
          placeholder={'请输入消息类型(0: 默认系统，扩展字段 )'}
      />
      <ProFormText
          rules={[
          {
          required: true,
          message: '消息内容为必填项',
          },
          ]}
          width="md"
          name="content"
          label={'消息内容'}
          placeholder={'请输入消息内容'}
      />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(TUserMsgUrl, value, currentRow);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<TUserMsgType>
            column={2}
            title={currentRow?.id}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<TUserMsgType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
